package com.mvvm.ktnet.ui

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.view.View.OnTouchListener
import android.widget.FrameLayout
import com.android.ktx.context.dp
import com.android.ktx.context.sp2px
import com.mvvm.ktnet.R

class DragScaleViewKt : View, OnTouchListener {
    protected var screenWidth = 0
    protected var screenHeight = 0
    protected var lastX = 0
    protected var lastY = 0
    private var oriLeft = 0
    private var oriRight = 0
    private var oriTop = 0
    private var oriBottom = 0
    private var dragDirection = 0
    private val offset = 20
    protected var paint = Paint()
    protected var textPaint = Paint()
    private var isTop = false
    protected fun initScreenW_H() {
        screenHeight = resources.displayMetrics.heightPixels - 40
        screenWidth = resources.displayMetrics.widthPixels
        paint.style = Paint.Style.STROKE
        paint.strokeWidth = 4.0f
        paint.isAntiAlias = true
        textPaint.isAntiAlias = true
        textPaint.textSize = 14.sp2px.toFloat()
        textPaint.style = Paint.Style.FILL
        textPaint.textAlign = Paint.Align.CENTER
    }

    constructor(context: Context?, attrs: AttributeSet?, defStyle: Int) : super(
        context,
        attrs,
        defStyle
    ) {
        setOnTouchListener(this)
        initScreenW_H()
    }

    private var cententString: String? = ""

    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {
        setOnTouchListener(this)
        val array = getContext().obtainStyledAttributes(attrs, R.styleable.DragScaleView)
        if (array != null) {
            cententString = array.getString(R.styleable.DragScaleView_mytest)
        }
        initScreenW_H()
    }

    constructor(context: Context?) : super(context) {
        setOnTouchListener(this)
        initScreenW_H()
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        init()
        Log.e("sss", "这里会重新走")
        canvas.drawRect(
            offset.toFloat(), offset.toFloat(), (width - offset).toFloat(), (height
                    - offset).toFloat(), paint
        )
        val fontMetrics = textPaint.fontMetrics
        val top = fontMetrics.top
        val bootom = fontMetrics.bottom
        canvas.drawText(
            cententString!!, (
                    offset + (width - offset - offset) / 2).toFloat(),
            offset + (height - offset - offset) / 2 + bootom - (bootom - top) / 2,
            textPaint
        )
    }

    private fun init() {
        if (isTop) {
            paint.color = Color.RED
            textPaint.color = Color.RED
        } else {
            paint.color = Color.GRAY
            textPaint.color = Color.GRAY
        }
    }

    fun setTop(top: Boolean) {
        isTop = top
        invalidate()
    }

    fun setContent(cententString: String?) {
        this.cententString = cententString
    }

    private val needUpload = false
    override fun onLayout(changed: Boolean, left1: Int, top2: Int, right3: Int, bottom4: Int) {
        super.onLayout(changed, this.left1, top1, right1, bottom1)
        //        if (needUpload) layout(oriLeft, oriTop, oriRight, oriBottom);
//        layout(left, top, right, bottom);
    }

    override fun onTouch(v: View, event: MotionEvent): Boolean {
        val action = event.action
        if (action == MotionEvent.ACTION_DOWN) {
            v.bringToFront()
            setTop(true)
            Log.e("sss", "设置顶层")
            val frameLayout = parent as FrameLayout
            val count = frameLayout.childCount
            if (frameLayout != null) {
                if (count > 1) {
                    for (i in 0 until count) {
                        val child = frameLayout.getChildAt(i)
                        if (child !== v && child is DragScaleViewKt) {
                            child.setTop(false)
                        }
                    }
                }
            }
            //            v.setZ(100);
            oriLeft = v.left
            oriRight = v.right
            oriTop = v.top
            oriBottom = v.bottom
            lastY = event.rawY.toInt()
            lastX = event.rawX.toInt()
            dragDirection = getDirection(
                v, event.x.toInt(),
                event.y.toInt()
            )
        }
        // 处理拖动事件
        delDrag(v, event, action)
        invalidate()
        return false
    }

    protected fun delDrag(v: View, event: MotionEvent, action: Int) {
        when (action) {
            MotionEvent.ACTION_MOVE -> {
                val dx = event.rawX.toInt() - lastX
                val dy = event.rawY.toInt() - lastY
                when (dragDirection) {
                    LEFT -> left(v, dx)
                    RIGHT -> right(v, dx)
                    BOTTOM -> bottom(v, dy)
                    TOP -> top(v, dy)
                    CENTER -> center(v, dx, dy)
                    LEFT_BOTTOM -> {
                        left(v, dx)
                        bottom(v, dy)
                    }
                    LEFT_TOP -> {
                        left(v, dx)
                        top(v, dy)
                    }
                    RIGHT_BOTTOM -> {
                        right(v, dx)
                        bottom(v, dy)
                    }
                    RIGHT_TOP -> {
                        right(v, dx)
                        top(v, dy)
                    }
                }
                val lp =
                    FrameLayout.LayoutParams(
                        FrameLayout.LayoutParams.WRAP_CONTENT,
                        FrameLayout.LayoutParams.WRAP_CONTENT
                    )
                val view = parent as View
                if (dragDirection != CENTER) {
                    v.layout(oriLeft, oriTop, oriRight, oriBottom)
                    lp.setMargins(oriLeft, oriTop, view.right - oriRight, view.bottom - oriBottom)
                    v.layoutParams = lp
                } else {
                    lp.setMargins(left1, top1, view.right - right1, view.bottom - bottom1)
                    v.layoutParams = lp
                }
                lastX = event.rawX.toInt()
                lastY = event.rawY.toInt()
            }
            MotionEvent.ACTION_UP -> dragDirection = 0
        }
    }

    var left1 = 0
    var top1 = 0
    var right1 = 0
    var bottom1 = 0
    private fun center(v: View, dx: Int, dy: Int) {
        left1 = v.left + dx
        top1 = v.top + dy
        right1 = v.right + dx
        bottom1 = v.bottom + dy
        if (left1 < -offset) {
            left1 = -offset
            right1 = left1 + v.width
        }
        if (right1 > screenWidth + offset) {
            right1 = screenWidth + offset
            left1 = right1 - v.width
        }
        if (top1 < -offset) {
            top1 = -offset
            bottom1 = top1 + v.height
        }
        if (bottom1 > screenHeight + offset) {
            bottom1 = screenHeight + offset
            top1 = bottom1 - v.height
        }
        v.layout(left1, top1, right1, bottom1)
    }

    private fun top(v: View, dy: Int) {
        oriTop += dy
        if (oriTop < -offset) {
            oriTop = -offset
        }
        if (oriBottom - oriTop - 2 * offset < 200) {
            oriTop = oriBottom - 2 * offset - 200
        }
    }

    private fun bottom(v: View, dy: Int) {
        oriBottom += dy
        if (oriBottom > screenHeight + offset) {
            oriBottom = screenHeight + offset
        }
        if (oriBottom - oriTop - 2 * offset < 200) {
            oriBottom = 200 + oriTop + 2 * offset
        }
    }

    private fun right(v: View, dx: Int) {
        oriRight += dx
        if (oriRight > screenWidth + offset) {
            oriRight = screenWidth + offset
        }
        if (oriRight - oriLeft - 2 * offset < 200) {
            oriRight = oriLeft + 2 * offset + 200
        }
    }

    private fun left(v: View, dx: Int) {
        oriLeft += dx
        if (oriLeft < -offset) {
            oriLeft = -offset
        }
        if (oriRight - oriLeft - 2 * offset < 200) {
            oriLeft = oriRight - 2 * offset - 200
        }
    }

    protected fun getDirection(v: View, x: Int, y: Int): Int {
        val left = v.left
        val right = v.right
        val bottom = v.bottom
        val top = v.top
        if (x < 40 && y < 40) {
            return LEFT_TOP
        }
        if (y < 40 && right - left - x < 40) {
            return RIGHT_TOP
        }
        if (x < 40 && bottom - top - y < 40) {
            return LEFT_BOTTOM
        }
        if (right - left - x < 40 && bottom - top - y < 40) {
            return RIGHT_BOTTOM
        }
        if (x < 40) {
            return LEFT
        }
        if (y < 40) {
            return TOP
        }
        if (right - left - x < 40) {
            return RIGHT
        }
        return if (bottom - top - y < 40) {
            BOTTOM
        } else CENTER
    }

    val cutWidth: Int
        get() = width - 2 * offset
    val cutHeight: Int
        get() = height - 2 * offset

    companion object {
        private const val TOP = 0x15
        private const val LEFT = 0x16
        private const val BOTTOM = 0x17
        private const val RIGHT = 0x18
        private const val LEFT_TOP = 0x11
        private const val RIGHT_TOP = 0x12
        private const val LEFT_BOTTOM = 0x13
        private const val RIGHT_BOTTOM = 0x14
        private const val CENTER = 0x19
    }
}


//private fun addScalview() {
//    val dragScaleView = DragScaleViewKt(this)
//    dragScaleView.setContent("view $num")
//    dragScaleView.isClickable=true
//    val lp = FrameLayout.LayoutParams(
//        120.dp,
//        120.dp
//    )
//    dragScaleView.layoutParams = lp
//
//    num++
//    val number = mDatabind.flRoot.childCount
//    if (number > 0) {
//        for (i in 0..number) {
//            val view = mDatabind.flRoot.getChildAt(i)
//            if (view != null && view is DragScaleViewKt) {
//                view.setTop(false)
//            }
//        }
//    }
//    mDatabind.flRoot.addView(dragScaleView)
//    dragScaleView.setTop(true)
//}